#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
@Time    : 2019-10-09 18:59
@Author  : wangb
@Email   : joker_wb@163.com
@File    : get_imgs.py
@Software: PyCharm
"""
import time
import multiprocessing as mp
import utils.configloader as cfg
from utils.image_utils import choose_rois
import cv2


def image_put(q1,q2):
    cap = cv2.VideoCapture(cfg.video_source('video'))
    rois = cfg.region_position()
    while True:
        start = time.time()
        if time.time() - start > cfg.detection_interval():
            q2.put(choose_rois(img=cap.read()[1],rois=rois))
        else:
            q1.put(cap.read()[1])
            q1.get() if not q1.empty() else time.sleep(0.01)


def image_get(q, window_name):
    cv2.namedWindow(window_name, flags=cv2.WINDOW_FREERATIO)
    while True:
        frame = q.get()
        cv2.imshow(window_name, frame)
        cv2.waitKey(1)


def run_single_camera(q1,q2):

    mp.set_start_method(method='spawn')  # init
    processes = [mp.Process(target=image_put, args=(q1,q2,)),
                 mp.Process(target=image_get, args=(q1, 1))]

    [process.start() for process in processes]
    [process.join() for process in processes]


if __name__ == '__main__':
    q1 = mp.Queue(2)
    q2 = mp.Queue(2)
    run_single_camera(q1,q2)